package com.example.petstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.petstore.entity.LoginDTO;
import com.example.petstore.entity.User;
import com.example.petstore.entity.UserLoginVO;
import com.example.petstore.exception.BaseException;
import com.example.petstore.exception.LoginFailedException;
import com.example.petstore.mapper.UserMapper;
import com.example.petstore.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author DD
 * @since 2024-07-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private  UserMapper userMapper;
    @Override
    public UserLoginVO login(LoginDTO loginDTO) {
        if (loginDTO.equals(null)){
            throw new LoginFailedException("登录错误");
        }
        // 创建一个 QueryWrapper 来添加查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", loginDTO.getUserAccount()); // 假设 username 是 User 实体中的一个字段
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1==null){
            throw new LoginFailedException("登录错误");
        }
        if(user1.getUserPassword().equals(loginDTO.getUserPassword())){
            UserLoginVO userLoginVO =new UserLoginVO();
            BeanUtils.copyProperties(user1,userLoginVO);
            return userLoginVO;
        }else {
            throw new LoginFailedException("密码错误");
        }

    }

    @Override
    public void register(LoginDTO loginDTO) {
//        1判断账号在库中是否存在
        try {
            // 检查是否已有相同账号的用户
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_account", loginDTO.getUserAccount());
            User existingUser = userMapper.selectOne(queryWrapper);

            if (existingUser != null) {
                // 如果找到相同的账号，则抛出异常
                throw new BaseException("已有账号请换一个账号");
            }
            User user1 = new User();
            BeanUtils.copyProperties(loginDTO,user1);
            user1.setCreateTime(LocalDateTime.now());
            // 如果没有找到相同账号的用户，则尝试插入新用户
            userMapper.insert(user1);
        } catch (Exception e) {
            // 记录异常信息，并抛出一个更友好的运行时异常
            log.error("注册用户失败", e);
            throw new RuntimeException("注册失败，请稍后重试。");
        }

    }
}
